// udpsender.cpp
#include "udpsender.h"
#include <QDebug>

UdpSender::UdpSender(const QHostAddress& ip, quint16 port, QObject* parent)
    : QObject(parent), m_socket(new QUdpSocket(this)), m_ip(ip), m_port(port)
{}

quint8 UdpSender::calculateChecksum(const quint8* data, quint8 length) {
    quint8 sum = 0;
    for (quint8 i=0; i<length; i++) sum += data[i];
    return sum;
}

void UdpSender::sendPacket(quint8 source, const QByteArray& payload) {
    ProtocolHeader header {0xA5, 0x5A, source, static_cast<quint8>(payload.size())};

    QByteArray packet;
    packet.append(reinterpret_cast<char*>(&header), sizeof(header));
    packet.append(payload);

    quint8 checksum = calculateChecksum(reinterpret_cast<const quint8*>(packet.data())+2,
                                        packet.size()-2);
    packet.append(static_cast<char>(checksum));
    packet.append(static_cast<char>(0xFF));

    m_socket->writeDatagram(packet, m_ip, m_port);
    qDebug() << "Send packet src:" << source << " size:" << packet.size();
}

void UdpSender::sendCar1(const CarData& data) {
    QByteArray payload(reinterpret_cast<const char*>(&data), sizeof(data));
    sendPacket(0x01, payload);
}

void UdpSender::sendCar2(const CarData& data) {
    QByteArray payload(reinterpret_cast<const char*>(&data), sizeof(data));
    sendPacket(0x02, payload);
}

void UdpSender::sendDrone(const DroneData& data) {
    QByteArray payload(reinterpret_cast<const char*>(&data), sizeof(data));
    sendPacket(0x03, payload);
}
